const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const query = this.get()

    if (query.title) {
      query.title = ['like', `%${query.title}%`]
    }

    delete query.page
    delete query.size

    const model = this.model('activity_list');
    const data = await model.where(query).order(['id DESC']).page(page, size).countSelect();

    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('activity_list');

    if (id > 0) {
      await this.model('activity_list').where({id: id}).update(values)
    } else {
      delete values.id;

      const hasNews = await model.where({title: values.title}).find()
      if(!think.isEmpty(hasNews)){
        return this.fail(400, '名称已存在');
      }
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()']

      await model.add(values);
    }
    return this.success(values);
  }

  async deleteAction() {
    const id = this.get('id');
    await this.model('activity_list').where({id: id}).limit(1).delete();
    return this.success();
  }

  async applyListAction(){

    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const model = this.model('activity_apply');
    const data = await model.alias('a').join({
      table: 'activity_list',
      join: 'left',
      as: 'c',
      on: ['activity_id', 'id']
    }).join({
      table: 'user',
      join: 'left',
      as: 'd',
      on: ['user_id', 'id']
    }).field(['a.create_time', 'c.title', 'd.name', 'd.nickname', 'd.is_vip', 'd.company', 'd.position', 'd.mobile']).order(['a.id DESC']).page(page, size).countSelect();

    return this.success(data);
  }

};
